<?php
require_once __DIR__ . '/../../functions.php';

// 检查管理员权限
if (!isAdmin()) {
    die('您没有权限访问此页面');
}

// 获取导出参数
$exportType = $_GET['export_type'] ?? 'all'; // all, selected, filtered
$selectedOrders = $_GET['selected_orders'] ?? '';
$format = $_GET['format'] ?? 'csv'; // csv, xlsx

// 获取筛选条件
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';
$user_id = $_GET['user_id'] ?? '';
$delivery_location = $_GET['delivery_location'] ?? '';
$order_platform = $_GET['order_platform'] ?? '';
$payment_method = $_GET['payment_method'] ?? '';
$group_name = $_GET['group_name'] ?? '';
$is_registered = $_GET['is_registered'] ?? '';
$settlement_type = $_GET['settlement_type'] ?? '';
$is_returned = $_GET['is_returned'] ?? '';
$is_signed = $_GET['is_signed'] ?? '';

// 构建查询条件
$where = ['1=1'];
$params = [];

if ($search) {
    $where[] = '(o.product_name LIKE ? OR o.tracking_no LIKE ? OR u.username LIKE ? OR u.phone LIKE ?)';
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($status && in_array($status, ['pending', 'settled', 'refunded'])) {
    $where[] = 'o.status = ?';
    $params[] = $status;
}

if ($user_id) {
    $where[] = 'o.user_id = ?';
    $params[] = intval($user_id);
}

if ($delivery_location) {
    $where[] = 'o.delivery_location = ?';
    $params[] = $delivery_location;
}

if ($order_platform) {
    $where[] = 'o.order_platform = ?';
    $params[] = $order_platform;
}

if ($payment_method) {
    $where[] = 'o.payment_method = ?';
    $params[] = $payment_method;
}

if ($group_name) {
    $where[] = 'u.group_name = ?';
    $params[] = $group_name;
}

if ($is_registered !== '') {
    $where[] = 'o.is_registered = ?';
    $params[] = intval($is_registered);
}

if ($settlement_type) {
    $where[] = 'o.settlement_type = ?';
    $params[] = $settlement_type;
}

if ($is_returned !== '') {
    $where[] = 'o.is_returned = ?';
    $params[] = intval($is_returned);
}

if ($is_signed !== '') {
    $where[] = 'o.is_signed = ?';
    $params[] = intval($is_signed);
}

// 处理选中的订单
if ($exportType === 'selected' && !empty($selectedOrders)) {
    $selectedIds = json_decode($selectedOrders, true);
    if (!empty($selectedIds)) {
        $placeholders = str_repeat('?,', count($selectedIds) - 1) . '?';
        $where[] = "o.id IN ($placeholders)";
        $params = array_merge($params, $selectedIds);
    }
}

$whereClause = implode(' AND ', $where);

// 获取订单数据
$db = getDB();
$sql = "SELECT o.*, u.username, u.phone, u.group_name FROM orders o 
        LEFT JOIN users u ON o.user_id = u.id 
        WHERE $whereClause 
        ORDER BY o.created_at DESC";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$orders = $stmt->fetchAll();

// 如果没有数据
if (empty($orders)) {
    die('没有符合条件的数据');
}

// 设置导出文件名
$filename = '订单导出_' . date('Y-m-d_H-i-s');

// CSV导出
if ($format === 'csv') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=' . $filename . '.csv');
    
    // 创建文件指针
    $output = fopen('php://output', 'w');
    
    // 输出BOM，解决中文乱码问题
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
    
    // 获取用户选择的导出字段
    $selectedFields = $_GET['fields'] ?? '';
    $fieldArray = [];
    
    if (!empty($selectedFields)) {
        $fieldArray = explode(',', $selectedFields);
    }
    
    // 定义所有可用的字段
    $allFields = [
        'id' => '订单ID',
        'product_name' => '商品名称',
        'delivery_location' => '收货地',
        'order_platform' => '下单平台',
        'tracking_no' => '物流单号',
        'order_amount' => '下单金额',
        'payment_method' => '付款方式',
        'username' => '用户名',
        'phone' => '手机号',
        'group_name' => '群组',
        'is_registered' => '登记状态',
        'settlement_type' => '结算类型',
        'is_returned' => '退还状态',
        'is_signed' => '签收状态',
        'status' => '订单状态',
        'settlement_amount' => '结算金额',
        'created_at' => '提交时间',
        'updated_at' => '更新时间'
    ];
    
    // 如果用户没有选择字段，使用默认字段
    if (empty($fieldArray)) {
        $exportFields = $allFields;
    } else {
        // 只导出用户选择的字段
        $exportFields = [];
        foreach ($fieldArray as $field) {
            if (isset($allFields[$field])) {
                $exportFields[$field] = $allFields[$field];
            }
        }
        
        // 如果没有有效的字段，使用默认字段
        if (empty($exportFields)) {
            $exportFields = $allFields;
        }
    }
    
    // 写入表头
    fputcsv($output, array_values($exportFields));
    
    // 写入数据
    foreach ($orders as $order) {
        $row = [];
        foreach ($exportFields as $field => $label) {
            switch ($field) {
                case 'delivery_location':
                    $row[] = getConfigOptionLabel('delivery_location', $order[$field]);
                    break;
                case 'order_platform':
                    $row[] = getConfigOptionLabel('order_platform', $order[$field]);
                    break;
                case 'payment_method':
                    $row[] = getPaymentMethodText($order[$field]);
                    break;
                case 'group_name':
                    $row[] = getConfigOptionLabel('group_name', $order[$field]);
                    break;
                case 'is_registered':
                    $row[] = $order[$field] ? '已登记' : '未登记';
                    break;
                case 'settlement_type':
                    $row[] = getSettlementTypeText($order[$field]);
                    break;
                case 'is_returned':
                    $row[] = $order[$field] ? '已退还' : '未退还';
                    break;
                case 'is_signed':
                    $row[] = $order[$field] ? '已签收' : '未签收';
                    break;
                case 'status':
                    $row[] = getOrderStatusText($order[$field]);
                    break;
                case 'created_at':
                case 'updated_at':
                    $row[] = formatTime($order[$field]);
                    break;
                default:
                    $row[] = $order[$field] ?? '';
            }
        }
        fputcsv($output, $row);
    }
    
    fclose($output);
    exit;
}

// Excel导出（简化版本，实际项目中可以使用PHPExcel库）
if ($format === 'xlsx') {
    // 这里使用简单的HTML表格导出为Excel
    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header('Content-Disposition: attachment; filename=' . $filename . '.xls');
    
    // 获取用户选择的导出字段
    $selectedFields = $_GET['fields'] ?? '';
    $fieldArray = [];
    
    if (!empty($selectedFields)) {
        $fieldArray = explode(',', $selectedFields);
    }
    
    // 定义所有可用的字段
    $allFields = [
        'id' => '订单ID',
        'product_name' => '商品名称',
        'delivery_location' => '收货地',
        'order_platform' => '下单平台',
        'tracking_no' => '物流单号',
        'order_amount' => '下单金额',
        'payment_method' => '付款方式',
        'username' => '用户名',
        'phone' => '手机号',
        'group_name' => '群组',
        'is_registered' => '登记状态',
        'settlement_type' => '结算类型',
        'is_returned' => '退还状态',
        'is_signed' => '签收状态',
        'status' => '订单状态',
        'settlement_amount' => '结算金额',
        'created_at' => '提交时间',
        'updated_at' => '更新时间'
    ];
    
    // 如果用户没有选择字段，使用默认字段
    if (empty($fieldArray)) {
        $exportFields = $allFields;
    } else {
        // 只导出用户选择的字段
        $exportFields = [];
        foreach ($fieldArray as $field) {
            if (isset($allFields[$field])) {
                $exportFields[$field] = $allFields[$field];
            }
        }
        
        // 如果没有有效的字段，使用默认字段
        if (empty($exportFields)) {
            $exportFields = $allFields;
        }
    }
    
    echo '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">';
    echo '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';
    echo '<head><meta charset="UTF-8"></head><body>';
    
    echo '<table border="1">';
    
    // 表头
    echo '<tr>';
    foreach ($exportFields as $label) {
        echo '<th>' . htmlspecialchars($label) . '</th>';
    }
    echo '</tr>';
    
    // 数据
    foreach ($orders as $order) {
        echo '<tr>';
        foreach ($exportFields as $field => $label) {
            switch ($field) {
                case 'delivery_location':
                    echo '<td>' . htmlspecialchars(getConfigOptionLabel('delivery_location', $order[$field])) . '</td>';
                    break;
                case 'order_platform':
                    echo '<td>' . htmlspecialchars(getConfigOptionLabel('order_platform', $order[$field])) . '</td>';
                    break;
                case 'payment_method':
                    echo '<td>' . htmlspecialchars(getPaymentMethodText($order[$field])) . '</td>';
                    break;
                case 'group_name':
                    echo '<td>' . htmlspecialchars(getConfigOptionLabel('group_name', $order[$field])) . '</td>';
                    break;
                case 'is_registered':
                    echo '<td>' . ($order[$field] ? '已登记' : '未登记') . '</td>';
                    break;
                case 'settlement_type':
                    echo '<td>' . htmlspecialchars(getSettlementTypeText($order[$field])) . '</td>';
                    break;
                case 'is_returned':
                    echo '<td>' . ($order[$field] ? '已退还' : '未退还') . '</td>';
                    break;
                case 'is_signed':
                    echo '<td>' . ($order[$field] ? '已签收' : '未签收') . '</td>';
                    break;
                case 'status':
                    echo '<td>' . htmlspecialchars(getOrderStatusText($order[$field])) . '</td>';
                    break;
                case 'created_at':
                case 'updated_at':
                    echo '<td>' . htmlspecialchars(formatTime($order[$field])) . '</td>';
                    break;
                default:
                    echo '<td>' . htmlspecialchars($order[$field] ?? '') . '</td>';
            }
        }
        echo '</tr>';
    }
    
    echo '</table></body></html>';
    exit;
}

// 如果没有匹配的格式
echo json_encode(['success' => false, 'message' => '不支持的导出格式']);
?>